public class Solution {
    String Serialize(TreeNode root) {
        if (root == null) {
            return "#";
        }
        StringBuilder sb = new StringBuilder();
        Queue q = new LinkedList();
        q.add(root);
        while (!q.isEmpty()) {
            int level_size = q.size();
            for (int i = 0; i < level_size; ++i) {
                TreeNode node = (TreeNode)q.remove();
                if (node == null) {
                    sb.append("#,");
                } else {
                    sb.append(node.val + ",");
                    q.add(node.left);
                    q.add(node.right);
                }
            }
        }
        return sb.toString().substring(0, sb.length() - 1);
    }
    TreeNode Deserialize(String str) {
        if (str == null || "#".equals(str)) {
            return null;
        }
        String[] nodes = str.split(",");
        TreeNode root = new TreeNode(Integer.parseInt(nodes[0]));
        Queue q = new LinkedList();
        q.add(root);
        for (int i = 1; i < nodes.length-1; ++i) {
            // 左子树
            TreeNode node = (TreeNode)q.remove();
            if (nodes[i].equals("#")) {
                node.left = null;
            } else {
                node.left = new TreeNode(Integer.parseInt(nodes[i]));
                q.add(node.left);
            }
            i++;
            // 右子树
            if (nodes[i].equals("#")) {
                node.right = null;
            } else {
                node.right = new TreeNode(Integer.parseInt(nodes[i]));
                q.add(node.right);
            }
        }
        return root;
    }
}